﻿using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;

namespace LocalTest.Infrastructure.Conventions;

public class StringLengthConvention : IModelFinalizingConvention
{
    public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder,
        IConventionContext<IConventionModelBuilder> context)
    {
        foreach (var property in modelBuilder.Metadata.GetEntityTypes().Where(entity => entity.BaseType == null)
                     .SelectMany(entity => entity.GetProperties().Where(p =>
                         p.ClrType == typeof(string) && p.GetConfigurationSource() == ConfigurationSource.Convention)))
        {
            if (property.Builder.CanSetMaxLength(255))
            {
                property.Builder.HasMaxLength(255);
            }
        }
    }
}